from flask import Flask,request,render_template,g,session,jsonify
from exts import db,mail
from models import UserModel,AtitudeDataModel,Fake_g_Model
from blueprint.auth import Bp as auth_Bp
from blueprint.display import  Bp as display_Bp
from flask_migrate import Migrate
import config
from flask import Flask
import decorators
from datetime import datetime,timedelta
import requests



app = Flask(__name__)

app.config.from_object(config)

#初始化db = SQLAlchemy()的app
db.init_app(app)

#mail对象邮箱的初始化
mail.init_app(app)

#将蓝图的页面与主页面进行关联,http//:localhost/auth/xx
app.register_blueprint(auth_Bp)
app.register_blueprint(display_Bp)

migrate = Migrate(app,db)
'''
在terminal（终端）中执行migrate三个步骤
（1）flask init
（2）flask migrate
（3）flask upgrade
'''


@app.route('/')
@decorators.login_required
def index():
    print("这是首页！")
    return render_template("index_2.html")


@app.route('/test')
def test():
    print("测试！")
    return render_template("test.html")

@app.before_request
def my_before_request():
    user_id = session.get("user_id")
    if user_id:
        user = UserModel.query.get(user_id)
        # user = db.session.get(UserModel, user_id)
        setattr(g, "user", user)
    else:
        setattr(g, "user", None)


@app.context_processor
def my_context_processor():
    return {"user": g.user}

# @app.route("/history")
# def history():
#     print("history")
#     return render_template("history.html")

# @app.route('/<data>',methods=['GET','POST'])
# def recieve_data(data):  # put application's code here
#
#     data1 = data
#     print(str(data1))
#     return 'OK'
#
# if __name__ == '__main__':
#     app.run(host='0.0.0.0', port=5001)
#

@app.route('/get_data_test', methods=['POST'])
def store_sensor_data():
    if request.method == 'POST':
        data = request.get_json()  # 假设传感器数据以JSON格式发送
        x_value = data.get('roll')
        y_value = data.get('pitch')
        z_value = data.get('yaw')
        print('roll'+str(x_value))
        print('pitch' + str(y_value))
        print('yaw'+str(z_value))


        if x_value is not None and y_value is not None and z_value is not None:
            sensor_data = AtitudeDataModel(roll=x_value,pitch=y_value,yaw=z_value)

            # 使用数据库框架将数据存储到数据库
            db.session.add(sensor_data)
            db.session.commit()

            return 'Sensor data stored successfully'

        return 'Invalid sensor data'

@app.route('/get_data_test11',methods=['GET','POST'])
def recieve_data():  # put application's code here
    data1 = request.get_json()  # 获取POST请求的JSON数据
    data2 = request.get_data()
    # 在这里处理接收到的数据
    # 您可以根据需要执行任何操作，如保存到数据库、进行计算等
    # 这里只是一个示例，将接收到的数据打印到控制台
    print("Received data:", data1)
    print(data2)
    return "Data received"  # 返回响应给8266设备

cnt1 = 0.668
cnt2 = 0.666
cnt3 = 0.999
@app.route('/real_time_data_show_test')
def real_time_data_show_test():
    global cnt1,cnt2,cnt3
    cnt1+= 1
    cnt2-= 2
    cnt3+= 3
    return {
        'cnt1': cnt1,
        'cnt2': cnt2,
        'cnt3': cnt3
    }

@app.route('/real_time_data_show')
def real_time_data_show():
    atitude_datas = AtitudeDataModel.query.order_by(AtitudeDataModel.id.desc()).first()
    roll = atitude_datas.roll
    pitch =atitude_datas.pitch
    yaw =atitude_datas.yaw
    # real_time = '2023年11月1日 15:41:59'
    real_time = atitude_datas.join_time
    return {
        'roll':roll,
        'pitch':pitch,
        'yaw':yaw,
        'time':real_time
    }

@app.route('/get_prams')
def get_prams_test():
    param = request.args.get('haha')
    return param


#找到 2023-11-06这一天的所有数据
@app.route('/filter_date_test')
def filter_date_test():
    start_date = datetime(2023, 11, 6)
    end_date = datetime(2023, 11, 10)
    results = AtitudeDataModel.query.filter(AtitudeDataModel.join_time.between(start_date, end_date)).all()

    for entry in results:
        print(entry.join_time)
    return 'ok'


# @app.route('/get_history_data')
# def get_history_data():
#     inputdate = request.args.get('inputdate')
#     start_date = datetime(2023, 11, 6)
#     end_date = start_date + timedelta(days=1)
#     results = AtitudeDataModel.query.filter(AtitudeDataModel.join_time.between(start_date, end_date)).all()
#
#     return results

@app.route('/get_history_data')
def get_history_data():
    inputdate = request.args.get('inputdate')
    input_date = datetime.strptime(inputdate, "%Y-%m-%d")

    start_date = input_date
    end_date = start_date + timedelta(days=1)

    results = AtitudeDataModel.query.filter(AtitudeDataModel.join_time.between(start_date, end_date)).all()

    # 将结果序列化为可传输的数据，例如字典列表
    serialized_data = []
    for entry in results:
        serialized_data.append({
            'id': entry.id,  # 替换为您的数据字段
            'roll': entry.roll,  # 替换为您的其他字段
            'pitch':entry.pitch,
            'yaw':entry.yaw,
            'time':entry.join_time
        })

    return jsonify(serialized_data)


@app.route('/get_time_slot',methods=['POST'])
def get_time_slot():
    start_date = request.form.get('start_date')
    end_date = request.form.get('end_date')
    print(start_date)
    print('start_date')
    print(end_date)
    print('end_date')

    results = AtitudeDataModel.query.filter(AtitudeDataModel.join_time.between(start_date, end_date)).all()

    # 将结果序列化为可传输的数据，例如字典列表
    serialized_data = []
    for entry in results:
        serialized_data.append({
            'id': entry.id,  # 替换为您的数据字段
            'roll': entry.roll,  # 替换为您的其他字段
            'pitch': entry.pitch,
            'yaw': entry.yaw,
            'time': entry.join_time
        })

    return jsonify(serialized_data)


@app.route('/binding/equip_id')
def equip_binding():
    equip_id = request.args.get("equip_id")
    url = "http://192.168.0.108/handle-command"
    data = {"command": f"{equip_id}"}
    response = requests.post(url, data=data)
    print(response.text)

    if equip_id == 'binding-led0':
        return 'binding-led0 success'
    elif equip_id == 'cancel-led0':
        return  'cancel-led0 success'
    return 'ok'





if __name__ == '__main__':
    app.debug = True
    app.run(host='0.0.0.0', port=5001)

# import socket
#
# localIP = "127.0.0.1"
# localPort = 3030
# bufferSize = 1024
# UDPServerSocket = socket.socket(family=socket.AF_INET, type=socket.SOCK_DGRAM)
# UDPServerSocket.bind((localIP, localPort))
# print("UDP server up and listening")
# while (True):
#     bytesAddressPair = UDPServerSocket.recvfrom(bufferSize)
#     message = bytesAddressPair[0]
#
#     if 'notify' in str(message):
#         try:
#             print('hello')
#         except:
#             print('sound error')
#     print(message)

